import os
import json
from urllib import parse, request
import base64
import pandas as pd
try:
    from . import gen_mask_to
    from .accuracy_mask import evaluation
    from .cvio import cvio
except:
    from testService import gen_mask_to
    from accuracy_mask import evaluation    
    from cvio import cvio

# 自动打标各租户测试图片
# 自动评估各租户识别率


def encodeImg(imgName):
    with open(imgName, 'rb') as f:
        data = f.read()
        encodestr = base64.b64encode(data)
    return encodestr


def detect_per_img(url, tenant, img):
    headers = dict(tenantId=tenant)
    img = encodeImg(img)
    data = dict(base64Data=img)
    data = parse.urlencode(data).encode('utf-8')
    req = request.Request(url, headers=headers, data=data)
    page = request.urlopen(req).read()
    page = bytes.decode(page)
    page = json.loads(page)
    return page

def get_tenants_products(src):
    xls = pd.read_excel(src)
    ID = xls['ID']
    SKU = xls['SKU名称编码']
    tenants_products = {}
    for idx, sku in zip(ID, SKU):
        idx = str(idx)
        if idx not in tenants_products:
            tenants_products[idx] = [sku]
        else:
            tenants_products[idx] += [sku]
    return tenants_products

def filter_other_products(result, products):
    xls = pd.read_excel(result, None)
    mAP = xls['mean AP']
    _mAP = {k: [] for k in mAP}
    for row in mAP.iloc():
        label = row[0]
        if label == 'mAP':
            continue
        dets = int(row[2])
        if dets == 0 and not label in products:
            continue
        else:
            for r, m in zip(row, _mAP):
                _mAP[m] += [r]
    pd.DataFrame(_mAP).to_excel(result, index=False)

def auto_eval_all_tenants(url, src, xlsp):
    def join(x): return os.path.join(*x)
    def exists(x): return os.path.exists(x)
    def isdir(x): return os.path.isdir(x)
    tenants = [f for f in os.listdir(src) if isdir(join((src, f)))]
    tenants_products = get_tenants_products(xlsp)

    for tid in tenants:
        if tid.startswith('-'):
            continue
        
        source = join((src, tid))
        imgs = cvio.load_image_list(source)
        if not len(imgs):
            continue
        saveroot = join((src, tid, 'predict'))
        if not exists(saveroot):
            os.makedirs(saveroot)
        for i, img in enumerate(imgs, 1):
            # if tid == '10122':
            #     continue
            print('%s [%d/%d] %s' % (tid, i, len(imgs), img))
            page = detect_per_img(url, tid, img)
            data = page['data']
            img = os.path.basename(img)
            gen_mask_to(saveroot, img, data,
                        filter_daiding=True, with_score=False)
        result = join((src, '%s.xlsx' % tid))
        evaluation(join((source, 'gt')), saveroot, result, print_summary=True)
        filter_other_products(result, tenants_products[tid])

if __name__ == '__main__':
    url = 'http://192.168.11.25:9998/detService/layerDet'
    src = r'G:\data\datasets\tester\tenants'
    tenants_products = r'C:\Users\Admin\Desktop\ProductManage.xls'
    auto_eval_all_tenants(url, src, tenants_products)
